# services/tools.py
from langchain.tools import tool
from PrivateChat.models import PrivateMessage
# services/tools.py
from langchain.tools import tool
from django.contrib.auth import get_user_model
User = get_user_model()
from asgiref.sync import sync_to_async

def check(user_name,target_user_name):
    sender_id = User.objects.get(username=user_name)
    target_id = User.objects.get(username=target_user_name)
    records = PrivateMessage.objects.filter(
        sender_id__in=[sender_id, target_id],
        receiver_id__in=[sender_id, target_id],
    ).order_by("timestamp")
    return records
def get_chat_history(input):
    """
    明确需要查询聊天记录时才使用
    获取两人之间的聊天记录。
    输入格式: "user_id,target_user_id"
    例如: "yuan,li"
    """
    try:
        user_name, target_user_name = input.split(",")
        # user_name = int(user_id.strip())
        # target_user_name = int(target_user_id.strip())
    except Exception:
        print(input)
        return "输入格式错误，请使用 'user_id,target_user_id'。"
    print(user_name, target_user_name)
    records = check(user_name,target_user_name)
    print(records)
    chats = []
    for r in records:
        # sender = "我" if r.sender.username == user_name else f"用户{r.sender.username}"
        chats.append(f"{r.sender}: {r.content}")

    return "\n".join(chats) if chats else "没有聊天记录。"

